package com.loiot.commons.jms;

/*
 * Timeloit.com Inc.
 * Copyright (c) 2012 时代凌宇物联网数据平台. All Rights Reserved
 */

import java.io.Serializable;
import java.util.HashMap;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

/**
 * @author yulianyu $Id$
 * 
 */
public class JmsSender {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private JmsTemplate jmsTemplate;

	public void sendMessage(final HashMap<String, Object> map, String topicName)
			throws JMSException {
		Topic topic = null;
		topic=new ActiveMQTopic(topicName);
		jmsTemplate.send(topic, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				ObjectMessage om = session.createObjectMessage(map);
				return om;
			}
		});
		logger.info("成功发送了一条JMS消息--JmsSender  topic:"+topicName);
	}

	public void sendSeriObj(final Serializable serializedObj, String topicName)
			throws JMSException {
		Topic topic = null;
		topic=new ActiveMQTopic(topicName);
		jmsTemplate.send(topic, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				ObjectMessage om = session.createObjectMessage(serializedObj);
				return om;
			}
		});
		logger.info("成功发送了一条JMS消息--JmsSender  topic:"+topicName);

	}
	/**
	 * 发送activemq byte message
	 * @param serializedObj
	 * @param topicName
	 * @throws JMSException
	 */
	public void sendSeriObjByte(final String jsonStr, String topicName)
			throws JMSException {
		Topic topic = null;
		topic=new ActiveMQTopic(topicName);
		jmsTemplate.send(topic, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				BytesMessage bm = session.createBytesMessage();
            	try {
					bm.writeBytes(jsonStr.getBytes());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            	
            	return bm;
			}
		});
		logger.info("成功发送了一条JMS消息--JmsSender  topic:"+topicName);

	}

	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}
}
